import Taro, {Component, Config} from '@tarojs/taro';
import {View} from '@tarojs/components';
import './index.scss';
import {HxPost} from '../../service/http';
import HxPage from '../../components/hxPage/hxPage';
import {AtButton} from 'taro-ui';
import {delay} from '../../utils/utils';
import {HxPay} from '../../utils/hx-pay';
import {HxTaro} from '../../utils/hx-taro';

export default class chargeDetail extends Component {
    constructor() {
        super(...arguments);
        this.state = {
            payItem: '0',// 0-充值 1-缴费
            ruleList: [],
            payWay: '0',// 0-农行支付 1-微信支付
            chargetype: '1',
            cardInfo: null,
            money: '',
            chargeAppId: '',
            orderId: '',
        };
    }

    private start = false;
    private startTime = 0;

    config: Config = {
        navigationBarTitleText: ''
    };

    getResult() {
        if (this.state['payWay'] === '0' && this.start) {
            Taro.showLoading({title: '查询支付结果...', mask: true});
            this.startTime = new Date().getTime();
            this.checkOrder();
        }
    }

    checkOrder() {
        if (new Date().getTime() - this.startTime > 60 * 1000) {
            this.start = false;
            Taro.hideLoading();
            HxTaro.toast('查询支付结果超时');
        } else {
            HxPost('payResult', {orderId: this.state['orderId']})
                .then((res) => {
                    if (res.payflag === '0') {
                        delay(5 * 1000)
                            .then(() => {
                                this.checkOrder();
                            });
                    } else {
                        this.start = false;
                        Taro.hideLoading();
                        Taro.navigateTo({
                            url: '/pages/chargeResult/index?payflag=' + res.payflag + '&payItem=' + this.state['payItem'] + '&money=' + this.state['money'] + '&rewardList=' + JSON.stringify(res.additionalMsg.bonusDetail || [])
                        });
                    }
                })
                .catch(() => {
                    delay(5 * 1000)
                        .then(() => {
                            this.checkOrder();
                        });
                });
        }

    }

    componentWillMount() {
        this.start = false;
        this.setState({
            chargeAppId: this.$router.params.chargeAppId,
            payItem: this.$router.params.orderId ? '1' : '0',
            orderId: this.$router.params.orderId,
            chargetype: this.$router.params.chargetype,
            cardInfo: JSON.parse(this.$router.params.cardInfo),
            money: this.$router.params.money
        });

        Taro.showLoading({title: '加载中...', mask: true})
            .then(() => {
                return HxPost('rewardInfo', {});
            })
            .then((res: any) => {
                this.setState({
                    ruleList: res.ruleList
                });
            })
            .catch((err) => {
                Taro.showToast({title: err.retMsg || '未知错误', icon: 'none', duration: 2 * 1000}).catch();
            })
            .finally(() => {
                Taro.hideLoading();
            });
    }

    goCharge() {
        Taro.showLoading({title: '加载中...', mask: true})
            .then(() => {
                if (this.state['payItem'] === '0') {// 充值
                    let param = {
                        chargetype: this.state['chargetype'],//1-自己充值  2-为他人充值
                        payChannelId: this.state['payWay'],
                        cardId: this.state['cardInfo']['cardId'],
                        amount: this.state['money'],
                        name: 'nickName',
                    };
                    return HxPost('order', param)
                        .then((res) => {
                            this.setState({
                                orderId: res.orderId,
                            });
                            Taro.hideLoading();
                            this.goPay(res.chargeAppId, res.chargePayUrl, res.wxPayExtendInfo);
                        })
                        .catch((err) => {
                            Taro.showToast({title: err.retMsg || '未知错误', icon: 'none', duration: 2 * 1000}).catch();
                        });
                } else {// 缴费
                    let param = {
                        payChannelId: this.state['payWay'],
                        chargeId: this.state['orderId'],
                    };
                    return HxPost('getPayUrl', param)
                        .then((res) => {
                            Taro.hideLoading();
                            this.goPay(this.state['chargeAppId'], res.payUrl, res.wxPayExtendInfo);
                        })
                        .catch((err) => {
                            Taro.showToast({title: err.retMsg || '未知错误', icon: 'none', duration: 2 * 1000}).catch();
                        });
                }
            });
    }

    goPay(chargeAppId, chargePayUrl,wxPayExtendInfo) {
        if (this.state['payWay'] === '0') {
            this.start = true;
        }

        const tips = this.state['payItem'] === '0' ? '充值完成，请查询“充值记录”' : '缴费完成后，请查看“已缴费”记录';
        HxPay.wxPay(chargeAppId, chargePayUrl,wxPayExtendInfo, tips, () => {
            if (this.state['payWay'] === '0') {
                this.getResult();
            } else {
                Taro.navigateBack({
                    delta: this.state['payItem'] === '0' ? 2 : 1
                }).catch();
            }
        }, this.state['payWay']);
    }

    changePayWay(payWay) {
        this.setState({
            payWay: payWay
        });
    }

    render() {
        const payList = [
            {name: '农行支付', icon: 'icon-nonghang1', value: '0'},
            {name: '微信支付', icon: 'icon-wechat_pay', value: '1'},
        ];
        // @ts-ignore
        const {payItem, payWay, ruleList, money, cardInfo} = this.state;
        return (
            <HxPage>
                <View
                    hidden={!cardInfo}
                    className='cardInfo'>
                    <View className='cardInfo_item'>
                        <View>机构</View>
                        <View>{cardInfo.companyname}</View>
                    </View>
                    <View className='cardInfo_item'>
                        <View>卡号</View>
                        <View>{cardInfo.cardId}</View>
                    </View>
                    <View className='cardInfo_item'>
                        <View>编号</View>
                        <View>{cardInfo.empnoId}</View>
                    </View>
                    <View className='cardInfo_item'>
                        <View>姓名</View>
                        <View>{cardInfo.name}</View>
                    </View>
                </View>

                <View className='charge_detail'>
                    <View className='charge_detail_item'>{payItem === '0' ? '充值' : '缴费'}金额</View>
                    <View className='charge_detail_item'>{money}元</View>
                </View>

                <View className='hxPayWay'>
                    <View className='hxPayWay_title'>支付方式</View>
                    <View className='hxPayWay_select'>
                        {
                            payList.map((item) => (
                                <View
                                    key={item.value}
                                    className='hxPayWay_select_item'
                                    onClick={this.changePayWay.bind(this, item.value)}>
                                    <View className={'icon iconfont hxPayWay_select_item_col ' + item.icon}/>
                                    <View className='hxPayWay_select_item_col'>{item.name}</View>
                                    <View
                                        className={
                                            'icon iconfont hxPayWay_select_item_col '
                                            + (item.value == payWay ? 'icon-radioactive' : 'icon-radio')
                                        }/>
                                </View>
                            ))
                        }
                    </View>
                    {
                        payWay === '0' && ruleList.length > 0 &&
                        <View className='tips'>
                            {
                                ruleList.map(item => <View key={item.description}
                                                           className='tips_son'>{item.description}</View>)
                            }
                        </View>
                    }
                </View>

                <AtButton
                    className="hxButton"
                    onClick={this.goCharge.bind(this)}>
                    立即支付
                </AtButton>
            </HxPage>
        );
    }
}
